package com.lottery.im.base;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者：cyy
 * 时间：2018/10/12 0012。
 */
public abstract class BaseRecyAdapter<T> extends RecyclerView.Adapter {

  protected abstract int getItemLayout();

  protected abstract int getBR();

  private List<T> mList = new ArrayList<>();

  public void addList(List<T>list){
    if(list!=null){
      mList.addAll(list);
      notifyDataSetChanged();
    }
  }

  public void notifyList(List<T>list){
    if(list!=null){
      mList=list;
      notifyDataSetChanged();
    }
  }

  public void setOnItemClickListener(BaseRecyAdapter.OnItemClickListener<T> onItemClickListener) {
    mOnItemClickListener = onItemClickListener;
  }

  protected BaseRecyAdapter.OnItemClickListener<T> mOnItemClickListener;

  public interface OnItemClickListener<T> {
    /**
     * @param position 点击位置
     * @param object 点击项
     */
    void onItemClick(int position, T object);
  }

  @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    ViewDataBinding dataBinding =
        DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()), getItemLayout(),
            viewGroup, false);
    return new MyViewHold(dataBinding);
  }

  @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int postion) {
    if(viewHolder instanceof MyViewHold){
      MyViewHold holder = (MyViewHold) viewHolder;
      holder.getBinding().setVariable(getBR(),mList.get(postion));
      holder.getBinding().executePendingBindings();

      holder.getBinding().getRoot().setOnClickListener(view -> {
        if(mOnItemClickListener!=null){
          mOnItemClickListener.onItemClick(postion,mList.get(postion));
        }
      });
    }
  }

  @Override public int getItemCount() {
    return mList.size();
  }

  static class MyViewHold extends RecyclerView.ViewHolder{
    private ViewDataBinding binding;

    public MyViewHold(ViewDataBinding binding) {
      super(binding.getRoot());
      this.binding=binding;
    }

    public  ViewDataBinding getBinding() {
      return binding;
    }
  }
}
